package com.sky.task;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.sky.entity.Orders;
import com.sky.mapper.OrdersMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.Date;
import java.util.List;

@Component
@Slf4j
public class OrderTask {
    @Autowired
    private OrdersMapper ordersMapper;

    /**
     * 每分钟的第0秒执行任务 处理订单超时
     */
    @Scheduled(cron = "0 * * * * ?")
//    @Scheduled(cron = "1/5 * * * * ?")
    public void handleOrderTimeout() {
        log.info("处理订单超时:{}", new Date());

        //将当前时间-15分钟 作为超时时间

        LocalDateTime time = LocalDateTime.now().plusMinutes(-15);
        //将LocalDateTime转换为Date类型
        Date date = Date.from(time.atZone(java.time.ZoneId.systemDefault()).toInstant());
        /**
         * 订单状态 1待付款 2待接单 3已接单 4派送中 5已完成 6已取消
         */
   /*     public static final Integer PENDING_PAYMENT = 1;
        public static final Integer TO_BE_CONFIRMED = 2;
        public static final Integer CONFIRMED = 3;
        public static final Integer DELIVERY_IN_PROGRESS = 4;
        public static final Integer COMPLETED = 5;
        public static final Integer CANCELLED = 6;*/
        LambdaQueryWrapper<Orders> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Orders::getStatus, Orders.PENDING_PAYMENT).lt(Orders::getOrderTime, date);
        List<Orders> orders = ordersMapper.selectList(wrapper);
        if (!CollectionUtils.isEmpty(orders)) {
            for (Orders order : orders) {
                //将超时的订单设置为已取消状态
                order.setStatus(Orders.CANCELLED);//设置订单状态为已取消
                order.setCancelTime(new Date());//设置取消时间
                order.setCancelReason("订单支付超时自动取消");//设置取消原因
                ordersMapper.update(order);
            }
        }


    }


    /**
     * 每天凌晨1点处理派送中的订单
     */
    @Scheduled(cron = "0 0 1 * * ?")
    public void handleDeliveryInProgress() {
        log.info("处理派送中的订单:{}", new Date());
        LocalDateTime time = LocalDateTime.now().plusMinutes(-60);
        //将LocalDateTime转换为Date类型
        Date date = Date.from(time.atZone(java.time.ZoneId.systemDefault()).toInstant());
        LambdaQueryWrapper<Orders> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Orders::getStatus, Orders.DELIVERY_IN_PROGRESS)//订单状态为派送中
                .lt(Orders::getOrderTime, date);
        List<Orders> orders = ordersMapper.selectList(wrapper);
        if (!CollectionUtils.isEmpty(orders)) {
            for (Orders order : orders) {
                //将超时的订单设置为已完成状态
                order.setStatus(Orders.COMPLETED);//设置订单状态为已完成
                ordersMapper.update(order);
            }
        }
    }

}
